package com.shuwen.gcdj.service.basicsstrategy;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.shuwen.gcdj.bean.AddResp;
import com.shuwen.gcdj.bean.DictResp;
import com.shuwen.gcdj.bean.VoidResp;
import com.shuwen.gcdj.bean.plan.request.CreateMaintainPlanReq;
import com.shuwen.gcdj.bean.strategy.request.*;
import com.shuwen.gcdj.bean.strategy.response.StrategyPageResp;
import com.shuwen.gcdj.bean.structure.request.DeleteFirstStructure;
import com.shuwen.gcdj.common.constant.Constants;
import com.shuwen.gcdj.common.exception.ApiException;
import com.shuwen.gcdj.dto.account.InitUserDto;
import com.shuwen.gcdj.entity.*;
import com.shuwen.gcdj.entity.basics.BasicsStrategy;
import com.shuwen.gcdj.mapper.mysql.*;
import com.shuwen.gcdj.mapper.mysql.basics.BasicsEquipmentMapper;
import com.shuwen.gcdj.service.BaseService;
import com.shuwen.gcdj.service.basicsstructure.BasicsStructureService;
import com.shuwen.gcdj.service.plan.PlanService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author :yys
 * @date : 2023/5/11 9:10
 */
@Service
@Slf4j
public class BasicsStrategyService extends BaseService<BasicsStrategyMapper, BasicsStrategy> {

    @Autowired
    private BasicsStrategyMapper basicsStrategyMapper;

    @Autowired
    private StrategyEquipmentstrategyrelMapper strategyEquipmentstrategyrelMapper;

    @Autowired
    private BasicsStructureMapper basicsStructureMapper;

    @Autowired
    private BasicsStructureService basicsStructureService;

    @Autowired
    private PlanDetailMapper planDetailMapper;

    @Autowired
    private PlanService planService;

    @Autowired
    private BasicsEquipmentMapper basicsEquipmentMapper;

    @Autowired
    private StrategyInspectionitemtemplaterelMapper strategyInspectionitemtemplaterelMapper;

    /**
     * 获取策略列表分页信息
     * @param req
     * @return
     */
    public Page<StrategyPageResp> getStrategypage(StrategyPageReq req) {
        Page<StrategyPageResp> page = new Page<>(req.getPageNum(), req.getPageSize(), true);
        IPage<StrategyPageResp> allList = basicsStrategyMapper.getStrategypage(page,req);
        List<StrategyPageResp> res = allList.getRecords();
        for(StrategyPageResp strategyPageResp : res){
            strategyPageResp.setEquipmentList(basicsStrategyMapper.getName(strategyPageResp.getId()));
        }
        Page<StrategyPageResp> resPage = new Page<>(page.getCurrent(), page.getSize(), allList.getTotal());
        resPage.setRecords(res);
        return resPage;

    }
//    添加策略
    public AddResp addStrategy(BasicsStrategy basicsStrategy,InitUserDto initUser, AddStrategyReq req){
        if(!StringUtils.isEmpty(req.getTemplateName()) && !StringUtils.isEmpty(req.getTemplateId())){
            basicsStrategy.setTemplateId(req.getTemplateId());
            basicsStrategy.setTemplateName(req.getTemplateName());
        }
        BeanUtil.copyProperties(req,basicsStrategy);
        basicsStrategy.setCreateId(initUser.getUserId());
        basicsStrategy.setUpdateId(initUser.getUserId());
        int insert = basicsStrategyMapper.insert(basicsStrategy);
        AddResp addResp = new AddResp();
        if(insert > 0){
            addResp.setId(basicsStrategy.getId());
        }
        return addResp;
    }


    /**
     * 添加策略
     * @param initUser
     * @param req
     * @return
     */
    public AddResp add(InitUserDto initUser, AddStrategyReq req) {
        BasicsStrategy basicsStrategy = new BasicsStrategy();
        AddResp addResp = addStrategy(basicsStrategy,initUser,req);
//        判断是否使用模板
        if(!StringUtils.isEmpty(req.getTemplateId())){
//            使用模板
//            部件表添加(一级，二级)
            LambdaQueryWrapper<BasicsStructure> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(BasicsStructure::getIsDelete,Constants.IS_DELETE_NORMAL)
                    .eq(BasicsStructure::getStrategyId,req.getTemplateId());
            List<BasicsStructure> basicsStructures = basicsStructureMapper.selectList(queryWrapper);
//            存所有的一级id
            List<String> ids = new ArrayList<>();
//            存所有新增的一级id
            List<String> newIds = new ArrayList<>();
//            添加一级设备
            for(BasicsStructure s : basicsStructures){

                if(s.getDepth() == 0){
                    String sid = s.getId();
                    ids.add(s.getId());
                    s.setId(null);
                    s.setCreateId(initUser.getUserId());
                    s.setUpdateId(initUser.getUserId());
                    s.setStrategyId(basicsStrategy.getId());
                    basicsStructureMapper.insert(s);
                    newIds.add(s.getId());
//              计划表添加（一级部件）
                    LambdaQueryWrapper<StrategyPlancycle> queryWrapperPlan = new LambdaQueryWrapper<>();
                    queryWrapperPlan.eq(StrategyPlancycle::getIsDelete,Constants.IS_DELETE_NORMAL)
                            .eq(StrategyPlancycle::getStructureId,sid);
                    StrategyPlancycle strategyPlancycle = new StrategyPlancycle();
                    strategyPlancycle = strategyPlancycle.selectOne(queryWrapperPlan);
                    strategyPlancycle.setId(null);
                    strategyPlancycle.setCreateId(initUser.getUserId());
                    strategyPlancycle.setUpdateId(initUser.getUserId());
                    strategyPlancycle.setStructureId(s.getId());
                    strategyPlancycle.setStrategyId(basicsStrategy.getId());
                    planService.save(strategyPlancycle);
                }

            }
//            添加二级设备
            for(BasicsStructure s : basicsStructures){
                addTwo(s,ids,newIds,initUser,basicsStrategy);
            }
        }
        return addResp;

    }
//    添加二级设备
    public void addTwo(BasicsStructure s,List<String> ids,List<String> newIds,InitUserDto initUser,BasicsStrategy basicsStrategy){
        if(s.getDepth() == 1){
            for(int i = 0 ; i<ids.size();i++){
                if(s.getParentId().equals(ids.get(i))){
                    String id = s.getId();
                    s.setId(null);
                    s.setCreateId(initUser.getUserId());
                    s.setUpdateId(initUser.getUserId());
                    s.setParentId(newIds.get(i));
                    s.setStrategyId(basicsStrategy.getId());
                    basicsStructureMapper.insert(s);
//            检查项中间表添加(二级部件)
                    LambdaQueryWrapper<StrategyInspectionitemtemplaterel> queryWrapperstr = new LambdaQueryWrapper<>();
                    queryWrapperstr.eq(StrategyInspectionitemtemplaterel::getIsDelete,Constants.IS_DELETE_NORMAL)
                            .eq(StrategyInspectionitemtemplaterel::getStructureId,id);
                    List<StrategyInspectionitemtemplaterel> strategyPlancycles = strategyInspectionitemtemplaterelMapper.selectList(queryWrapperstr);
                    for(StrategyInspectionitemtemplaterel st : strategyPlancycles){
                        st.setId(null);
                        st.setCreateId(initUser.getUserId());
                        st.setUpdateId(initUser.getUserId());
                        st.setStructureId(s.getId());
                        strategyInspectionitemtemplaterelMapper.insert(st);
                    }
                }
            }
        }
    }

    /**
     * 批量删除策略
     * @param req
     * @return
     */
    public VoidResp batchDelete(InitUserDto initUserDto,DeleteStrategyReq req) {
        if(req == null || CollectionUtils.isEmpty(req.getIds())){
            throw new ApiException("请选择要删除的策略");
        }
        for(String s : req.getIds()){
            BasicsStrategy basicsStrategy = basicsStrategyMapper.selectById(s);
            if(basicsStrategy == null){
                throw new ApiException("数据不存在"+s);
            }
//            获取所有一级设备id
            LambdaQueryWrapper<BasicsStructure> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(BasicsStructure::getStrategyId,s)
                    .eq(BasicsStructure::getDepth,0)
                    .eq(BasicsStructure::getIsDelete,Constants.IS_DELETE_NORMAL);
            List<BasicsStructure> basicsStructures = basicsStructureMapper.selectList(queryWrapper);
            List<String> ids = new ArrayList<>();
            for(BasicsStructure ss : basicsStructures){
                ids.add(ss.getId());
            }
            DeleteFirstStructure deleteFirstStructure = new DeleteFirstStructure();
            deleteFirstStructure.setIds(ids);
//            删除策略下的一级设备，二级设备，检查项模板关联信息,一级计划
            basicsStructureService.batchFirstStructure(initUserDto,deleteFirstStructure);
//            删除策略
            basicsStrategy.setUpdateTime(null);
            basicsStrategy.setIsDelete(Constants.IS_DELETE_YES);
            basicsStrategy.setUpdateId(initUserDto.getUserId());
            basicsStrategyMapper.updateById(basicsStrategy);
        }

        return new VoidResp();
    }

    /**
     * 修改策略名称，状态，模板
     * @param initUser
     * @param req
     * @return
     */
    public VoidResp editstrategyname(InitUserDto initUser, UpdateStrategyReq req) {
        BasicsStrategy basicsStrategy = basicsStrategyMapper.selectById(req.getId());
        if(basicsStrategy == null){
            throw new ApiException("当前策略不存在！");
        }
//        重命名
        if(!StringUtils.isEmpty(req.getName())){
            basicsStrategy.setName(req.getName());
            basicsStrategy.setUpdateTime(null);
            basicsStrategy.setUpdateId(initUser.getUserId());
            updateById(basicsStrategy);
            return new VoidResp();
        }
//        修改状态
        if(!StringUtils.isEmpty(req.getState())){
            basicsStrategy.setState(req.getState());
            basicsStrategy.setUpdateTime(null);
            basicsStrategy.setUpdateId(initUser.getUserId());
            updateById(basicsStrategy);
            return new VoidResp();
        }
//        修改是否是模板
        if(!StringUtils.isEmpty(req.getIsTemplate())){
            basicsStrategy.setIsTemplate(req.getIsTemplate());
            basicsStrategy.setUpdateTime(null);
            basicsStrategy.setUpdateId(initUser.getUserId());
            updateById(basicsStrategy);
            return new VoidResp();
        }
        return new VoidResp();
    }

    public AddResp editstrategylinkequipment(InitUserDto initUser, AssociateDeviceReq req) throws ParseException {
        LambdaQueryWrapper<StrategyEquipmentstrategyrel> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(StrategyEquipmentstrategyrel::getEquipmentId,req.getEquipmentId())
                .eq(StrategyEquipmentstrategyrel::getIsDelete,Constants.IS_DELETE_NORMAL);
        StrategyEquipmentstrategyrel strategyEquipmentstrategyrel = strategyEquipmentstrategyrelMapper.selectOne(wrapper);

        AddResp addResp = new AddResp();
        if(strategyEquipmentstrategyrel == null){
//            此设备没有关联策略，新增
            StrategyEquipmentstrategyrel strategyEquipmentstrategyrelone = new StrategyEquipmentstrategyrel();
            BeanUtil.copyProperties(req,strategyEquipmentstrategyrelone);
            strategyEquipmentstrategyrelone.setEquipmentId(req.getEquipmentId());
            strategyEquipmentstrategyrelone.setStrategyId(req.getStrategyId());
            strategyEquipmentstrategyrelone.setCreateId(initUser.getUserId());
            strategyEquipmentstrategyrelone.setUpdateId(initUser.getUserId());
            int insert = strategyEquipmentstrategyrelMapper.insert(strategyEquipmentstrategyrelone);
            if(insert < 1){
                throw new ApiException("策略关联设备失败");
            }
            addResp.setId(strategyEquipmentstrategyrelone.getId());
        }else{
//            此设备关联策略，编辑
            BeanUtil.copyProperties(req,strategyEquipmentstrategyrel);
            strategyEquipmentstrategyrel.setStrategyId(req.getStrategyId());
            strategyEquipmentstrategyrel.setUpdateId(initUser.getUserId());
            strategyEquipmentstrategyrel.setUpdateTime(null);
            int insert = strategyEquipmentstrategyrelMapper.updateById(strategyEquipmentstrategyrel);
            if(insert < 1){
                throw new ApiException("策略关联设备失败");
            }
            addResp.setId(strategyEquipmentstrategyrel.getId());
        }
//      删除与设备有关的计划详情
        LambdaQueryWrapper<StrategyPlandetail> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(StrategyPlandetail::getEquipmentId,req.getEquipmentId())
                .eq(StrategyPlandetail::getIsDelete,Constants.IS_DELETE_NORMAL);
        List<StrategyPlandetail> strategyPlandetails = planDetailMapper.selectList(queryWrapper);
//        for(StrategyPlandetail ss : strategyPlandetails){
//            ss.setUpdateId(initUser.getUserId());
//            ss.setIsDelete(Constants.IS_DELETE_YES);
//            planDetailMapper.updateById(ss);
//        }

        List<String> planDetailIds = strategyPlandetails.stream().map(sp->sp.getId()).collect(Collectors.toList());
        if(!CollectionUtils.isEmpty(planDetailIds))
        {
            planDetailMapper.updateIsdeleteBatchByIds(planDetailIds);
        }
//      设备生成新的计划详情
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd 00:00:00");
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        calendar.add(Calendar.DAY_OF_MONTH,1);
        String starTime = simpleDateFormat.format(calendar.getTime());
        String endTime = planService.getmaxexecdatebystrategyid(req.getEquipmentId());
//        计划详情没数据，不用生成
        if(endTime == null){
            return addResp;
        }
        CreateMaintainPlanReq createMaintainPlanReq = new CreateMaintainPlanReq();
        createMaintainPlanReq.setEndDate(endTime);
        createMaintainPlanReq.setStartDate(starTime);
        createMaintainPlanReq.setEquipmentId(req.getEquipmentId());
        planService.createmaintainplandetailByStrategy(initUser,createMaintainPlanReq,req);
        return addResp;
    }

    /**
     * 获取关联设备
     * @param req
     * @return
     */
    public List<DictResp> getEquipment(QueryEmentReq req) {

        return basicsEquipmentMapper.getEquipment(req);
    }

    public List<StrategyPageResp> getstategytemplatelist() {
        return basicsStrategyMapper.getstategytemplatelist();
    }
}
